#!/bin/bash

#从各大区拉取每日数据
root_dir="/data/home/app100711417/tony"

from_file="${root_dir}/pull_data/zone.cfg"
to_file="${root_dir}/pull_data/dst_db.cfg"
sh_daily="${root_dir}/osssql/daily.sh"

#汇总db的配置
to_ip=""
to_port=""
to_user=""
to_passwd=""
to_gameDB=""
to_ossDB=""
while read -r ip port user passwd gameDB ossDB
do
    if [[ ${ip:0:1} == "#" ]] || [[ ${#ip} -lt 4 ]] ; then
        continue;
    fi
	
	to_ip=$ip  to_port=$port to_user=$user to_passwd=$passwd  to_ossDB=$ossDB to_gameDB=$gameDB
	#echo "target info:" $to_ip $to_port $to_user $to_passwd $to_ossDB  
	break;
done < ${to_file}

log_file="${root_dir}/pull_data/pull_daily.log"
#echo $tmp_file
while read -r zoneid ip port user passwd gameDB ossDB
do
	#过滤掉空行和注释行
	#echo $zoneid,  ${#zoneid}, $ip
	if [[ ${zoneid:0:1} == "#" ]] || [[ ${#ip} -lt 1 ]] ; then
		continue;
	fi
	
	tmp_file="${root_dir}/pull_data/oss_tmp_${zoneid}.dat"

	#获取拉数据的时间
	update_time=`mysql -h ${to_ip} -P${to_port} -u${to_user} -p${to_passwd} -N -e "select max(UpdateDate) from ${to_ossDB}.TDailyData where ZoneID = ${zoneid}"`
	if [ "$update_time" == "NULL" ]; then
		update_time=`mysql -h ${ip} -P ${port} -u${user} -p${passwd} -N -e "select min(UpdateDate) from ${gameDB}.TOssPlayerData"`
	else		
		update_time=`date -d "$update_time +1 day" +%Y-%m-%d` 
		if [ $update_time == `date +%Y-%m-%d` ] ;  then
			echo "can't generate data of today, try tomorrow! zone: $zoneid"
			continue;
		fi
	fi

	echo "source info: $ip ${port} ${ossDB} ${#ossDB}" " at data" ${update_time} -@-
	
	#在远端生成当日的统计数据
	sh $sh_daily ${ip} ${port} ${user} ${passwd} $update_time  >> pull_daily.log

	#导出数据   	
    mysqldump -h ${ip} -P ${port} -u${user} -p${passwd} --no-create-info \
			--ignore-table=${ossDB}.TOssMoneySection  ${ossDB}\
			-w "date(UpdateDate) = \"${update_time}\"" > ${tmp_file}
	
    #导入数据
	mysql -h ${to_ip} -P ${to_port} -u${to_user} -p${to_passwd} ${to_ossDB} < ${tmp_file}  >> ${log_file}

	rm -f ${tmp_file}
done < $from_file


